﻿using famails.bus;
using famails.common;
using FAMailUtils.Data.DAO;
using FAMailUtils.Data.DTO;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OnlineBusinesses.Areas.CustomerAdmin
{
    public partial class ClientDetail : System.Web.UI.Page
    {
        static ClientDAO dao = new ClientDAO();
        ClientBUS clientbus;
        ClientRegisterBUS clientRegister;
        ClientFunctionBUS clientFunction;
        PackageBUS pkgBus;
        PackageLimitBUS pkglimitBus;
        FunctionBUS function;
        UserLoginDTO userLogin = null;
        string imagePath = "images/clientlogo";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                userLogin = getUserLogin();
                LoadData();
                Page.Header.Title = "Thông tin tài khoản!!!";
            }
        }
        private UserLoginDTO getUserLogin()
        {
            userLogin = (UserLoginDTO)Session["UserLogin"];
            if (userLogin == null)
                Response.Redirect(ResolveUrl("~/login.aspx"));
            else return userLogin;
            return null;
        }
        private void LoadData()
        {
            try
            {
                #region LoadData
                if (userLogin.Client.UserID > 0)
                {
                    //int user = Convert.ToInt32(Request.QueryString["user"].ToString());
                    int user = userLogin.Client.UserID;
                    clientbus = new ClientBUS();
                    DataTable dtClient = new DataTable();
                    dtClient = clientbus.GetByID(user);
                    string email = dtClient.Rows[0]["email"] + "";
                    int registerId = Convert.ToInt32(dtClient.Rows[0]["registerId"].ToString());
                    int clientId = Convert.ToInt32(dtClient.Rows[0]["clientId"].ToString());
                    clientRegister = new ClientRegisterBUS();
                    DataTable dtClientRegister = new DataTable();
                    dtClientRegister = clientRegister.GetbyID(registerId);
                    string packageid = dtClientRegister.Rows[0]["packageId"].ToString();
                    DataTable dtpackage = new DataTable();
                    pkgBus = new PackageBUS();
                    dtpackage = pkgBus.GetById(Convert.ToInt32(packageid));
                    int packagelimitid = Convert.ToInt32(dtClientRegister.Rows[0]["limitid"].ToString());
                    DataTable dtlimit = new DataTable();
                    pkglimitBus = new PackageLimitBUS();
                    dtlimit = pkglimitBus.GetByUserIdPackageLimit(packagelimitid);
                    string SoluongEmail = "";
                    if (dtpackage.Rows.Count > 0)
                    {
                        lblTenGoi.Text = dtpackage.Rows[0]["packageName"].ToString();
                        SoluongEmail = dtpackage.Rows[0]["isUnlimit"].ToString();
                        if (SoluongEmail.Trim() != "True")
                        {
                            SoluongEmail = dtpackage.Rows[0]["emailCount"].ToString();
                            lblSoLuongEmail.Text = SoluongEmail;
                        }
                        else
                        {
                            lblSoLuongEmail.Text = "Không giới hạn";
                        }
                    }
                    if (dtClient.Rows[0]["activeDate"] + "" != "")
                        lblNgayKichHoat.Text = Convert.ToDateTime(dtClient.Rows[0]["activeDate"]).ToString("dd/MM/yyyy");
                    if (dtClient.Rows[0]["expireDate"] + "" != "")
                        lblNgayDenHan.Text = Convert.ToDateTime(dtClient.Rows[0]["expireDate"]).ToString("dd/MM/yyyy");
                    //if (Convert.ToDateTime(dtClient.Rows[0]["expireDate"]) < DateTime.Now)
                    //    lblNgayDenHan.Text = Convert.ToDateTime(dtClient.Rows[0]["expireDate"]).ToString("dd/MM/yyyy'(<label style=\"color:red\">Đã hết hạn)</label>'");
                    lblSoTaiKhoanCon.Text = dtClientRegister.Rows[0]["subAccontCount"].ToString();

                    string GioihanEmail = dtlimit.Rows[0]["isUnlimit"].ToString();
                    if (GioihanEmail.Trim() != "True")
                    {
                        GioihanEmail = dtlimit.Rows[0]["under"].ToString();
                        lblGioiHanEmail.Text = Convert.ToDecimal(GioihanEmail).ToString("#,###");
                    }
                    else
                    {
                        lblGioiHanEmail.Text = "Không giới hạn";
                    }
                    clientFunction = new ClientFunctionBUS();
                    DataTable dtfunction = new DataTable();
                    dtfunction = clientFunction.GetByregisterIdandclientId(registerId, clientId);
                    if (dtfunction != null && dtfunction.Rows.Count > 0)
                    {
                        DataTable dtTemp = new DataTable();
                        dtTemp.Columns.Add("functionName", typeof(String));
                        foreach (DataRow drfunction in dtfunction.Rows)
                        {
                            DataRow dr = dtTemp.NewRow();
                            function = new FunctionBUS();
                            string idFunction = drfunction["functionId"].ToString();
                            DataTable dtTemp2 = function.GetByFunctionId(Convert.ToInt32(idFunction));
                            if (dtTemp2 != null && dtTemp2.Rows.Count > 0)
                            {
                                string FunctionName = dtTemp2.Rows[0]["functionName"].ToString();
                                dr["functionName"] = FunctionName;
                                dtTemp.Rows.Add(dr);
                            }
                        }

                        rptFunction.DataSource = dtTemp;
                        rptFunction.DataBind();
                    }

                    lblEmail.Text = email;

                    if (((AdminCustomer_Master)Page.Master).getUserLogin() == null) return;
                    FAMailUtils.Data.DTO.ClientDTO company = dao.GetByClientID(((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);

                    CompanyLogo.Src = company.CompanyLogo;
                    txtCompanyEmail.Text = company.CompanyEmail;
                    txtCompanyAddress.Text = company.CompanyAddress;
                    txtCompanyFax.Text = company.CompanyFax;
                    txtCompanyName.Text = company.CompanyName;
                    txtCompanyPhone.Text = company.CompanyPhone;

                    DateTime today = DateTime.Now.Date;

                    DateTime dateexpire = DateTime.Now;

                    if (DateTime.TryParse(dtClient.Rows[0]["expireDate"] + "", out dateexpire) && dateexpire < today)
                    {
                        btnGiahan.Enabled = true;
                        btnGiahan.Text = "(Đã hết hạn " + (today - dateexpire).TotalDays + " ngày)";
                    }
                    else
                    {
                        btnGiahan.Enabled = false; ;
                        btnGiahan.CssClass = "button round image-right ic-add text-upper";
                        btnGiahan.Text = "(Còn lại " + (dateexpire - today).TotalDays + " ngày)";
                    }

                    DataTable dtClientRegisterUnPay = clientRegister.GetUnPaymentByClientID(clientId);
                    if (dtClientRegisterUnPay != null && dtClientRegisterUnPay.Rows.Count > 0)
                    {
                        pnlThanhToan.Visible = true;
                        formExtend.Visible = false;
                        btnExtend.Disabled = btnUpgrade.Disabled = true;
                        btnGiahan.Enabled = false;
                        hdfUnPaidRegisterID.Value = dtClientRegisterUnPay.Rows[0]["registerid"] + "";
                    }
                }
                #endregion

            }
            catch (Exception ex)
            {
                Common.logs(Request.RawUrl + "-" + FAMailUtils.Common.GetCurrentMethod(), ex, Common.logType.error);
                pnError.Visible = true;
                lblError.Text = "Có lỗi trong quá trình nạp dữ liệu!" + ex.Message.ToString();
            }
        }
        

        protected void btnGiahan0_Click(object sender, EventArgs e)
        {
            Response.Redirect("packagechange.aspx?type=editoption");
        }
        protected void btnGiahan_Click(object sender, EventArgs e)
        {
            Response.Redirect("PackageChange.aspx?type=extend");
        }
        protected void btnUpGradeServices_Click(object sender, EventArgs e)
        {
            Response.Redirect("packagechange.aspx?type=upgrade");
        }

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
        public static void Save(string email, string name, string phone, string fax, string address, string logo)
        {
            try
            {
                UserLoginDTO user = (UserLoginDTO)HttpContext.Current.Session["UserLogin"];
                FAMailUtils.Data.DTO.ClientDTO company = dao.GetByClientID(user.Client.ClientID);
                company.CompanyEmail = email;
                company.CompanyAddress = address;
                company.CompanyFax = fax;
                company.CompanyName = name;
                company.CompanyPhone = phone;
                company.CompanyLogo = logo;
                dao.Update(company);

                user.Client.CompanyLogo = logo;
                HttpContext.Current.Session["UserLogin"] = user;
            }
            catch (Exception ex)
            {
                Common.logs(HttpContext.Current.Request.RawUrl + "-" + FAMailUtils.Common.GetCurrentMethod(), ex, Common.logType.error);
            }
        }
        

        protected void deletefile_Click(object sender, EventArgs e)
        {
            //string newFile = hdfImage.Value;
            //string filePath = Server.MapPath("../../" + newFile);
            //File.Delete(filePath);
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            clientbus = new ClientBUS();
            if (clientbus.CancelTransaction(hdfUnPaidRegisterID.Value))
            {
                btnUpgrade.Disabled = btnExtend.Disabled = false;
                pnlThanhToan.Visible = false;
                pnError.Visible = false;
                pnSuccess.Visible = true;
                formExtend.Visible = true;
                lblSuccess.Text = "Huỷ thành công";
            }
        }
    }
}